<template>
  <el-config-provider :locale="zhCn">
    <div class="tag-manage">
      <!-- 筛选条件区域 -->
      <filter-form v-model="filterForm" :form-items="formItems" @search="handleSearch" @reset="resetFilter" />

      <!-- 选项卡区域 -->
      <el-tabs type="card" v-model="activeTab" class="notice-tabs" @tab-click="handleTabClick">
        <el-tab-pane label="好友列表" name="friend">
          <!-- 列表展示区域 -->
          <div class="table-section">
            <div class="operation-section">
              <el-button type="success" @click="handleCreateTag">新增标签</el-button>
              <el-button type="warning" @click="handleConfigFriendTag">批量配置标签</el-button>
            </div>
            <el-table :data="friendList" border style="width: 100%" v-loading="loading" class="custom-table">
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column :label="infoColumnLabel" min-width="100">
                <template #default="{ row }">
                  <ai-wechat-info :avatar-url="row.avatar" :user-name="row.nickname" />
                </template>
              </el-table-column>
              <el-table-column label="标签" min-width="200">
                <template #default="{ row }">
                  <div v-if="row.tags && row.tags.length > 0" class="tag-list">
                    <el-tag v-for="tag in row.tags" :key="tag.id" class="tag-item" closable @close="handleRemoveTag(row, tag)">
                      {{ tag.label_name }}
                    </el-tag>
                  </div>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" link @click="handleAddTag(row)">编辑</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <el-tab-pane label="群聊列表" name="group">
          <!-- 列表展示区域（复用同一套表格与操作） -->
          <div class="table-section">
            <div class="operation-section">
              <el-button type="success" @click="handleCreateTag">新增标签</el-button>
              <el-button type="warning" @click="handleConfigFriendTag">批量配置标签</el-button>
            </div>
            <el-table :data="friendList" border style="width: 100%" v-loading="loading" class="custom-table">
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column :label="infoColumnLabel" min-width="100">
                <template #default="{ row }">
                  <!-- 好友信息使用 ai-wechat-info 组件 -->
                  <ai-wechat-info v-if="activeTab === 'friend'" :avatar-url="row.avatar" :user-name="row.nickname" />
                  <!-- 群聊信息居中布局 -->
                  <div v-else class="group-info-centered">
                    <div class="group-avatar-centered">
                      <div
                        v-if="row.groupUrlList && row.groupUrlList.length > 0"
                        class="group-avatar"
                        :class="'avatar-count-' + Math.min(row.groupUrlList.length, 9)"
                      >
                        <div v-for="(url, index) in row.groupUrlList" :key="index" class="group-avatar-item">
                          <img :src="url" :alt="'群成员' + (index + 1)" />
                        </div>
                      </div>
                      <div v-else class="default-group-avatar">
                        <div class="group-avatar avatar-count-1">
                          <div class="group-avatar-item">
                            <img src="/src/assets/avatar1.jpg" alt="群聊" />
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="group-name-centered">
                      {{ row.nickname || '-' }}
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="标签" min-width="200">
                <template #default="{ row }">
                  <div v-if="row.tags && row.tags.length > 0" class="tag-list">
                    <el-tag v-for="tag in row.tags" :key="tag.id" class="tag-item" closable @close="handleRemoveTag(row, tag)">
                      {{ tag.label_name }}
                    </el-tag>
                  </div>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column label="成员数" min-width="30">
                <template #default="{ row }">
                  <span>{{ row.memberCount || 0 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" link @click="handleAddTag(row)">编辑</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>

      <!-- 分页 -->
      <pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total" @pagination="handlePagination" />

      <!-- 筛选条件选择标签对话框 -->
      <tag-select-dialog
        v-model="filterTagSelectDialogVisible"
        :multiple="true"
        :selected-tags="filterForm.labels"
        title="选择标签"
        @confirm="handleFilterTagSelectConfirm"
        @cancel="filterTagSelectDialogVisible = false"
      />

      <!-- 新增标签对话框 -->
      <el-dialog v-model="createTagDialogVisible" title="新增标签" width="500px" destroy-on-close class="tag-dialog">
        <div class="tag-content">
          <div class="existing-tags" v-if="tagList.length > 0">
            <div class="section-title">已配置标签</div>
            <div class="tag-list">
              <el-tag
                v-for="tag in tagList"
                :key="tag.id"
                class="tag-item"
                :class="{ 'protected-tag': isProtectedTag(tag.label_name) }"
                :closable="!isProtectedTag(tag.label_name)"
                @close="handleDeleteTag(tag)"
              >
                <span :class="{ clickable: !isProtectedTag(tag.label_name) }" @click="!isProtectedTag(tag.label_name) && handleEditTag(tag)">
                  {{ tag.label_name }}
                  <el-icon v-if="isProtectedTag(tag.label_name)" class="protected-icon">
                    <Lock />
                  </el-icon>
                </span>
              </el-tag>
            </div>
          </div>
          <div class="new-tags">
            <div class="section-title">自定义标签</div>
            <div style="display: flex; gap: 8px">
              <el-input v-model="newTagInput" placeholder="请输入标签名称" class="tag-input" :prefix-icon="PriceTag"> </el-input>
              <el-button type="success" style="height: 32px" @click="handleAddNewTag">新增</el-button>
            </div>
          </div>
        </div>
      </el-dialog>

      <!-- 添加标签对话框 -->
      <el-dialog v-model="addTagDialogVisible" title="编辑标签" width="500px" destroy-on-close class="tag-dialog">
        <el-form :model="addTagForm" label-width="80px" class="tag-form">
          <el-form-item label="选择标签" style="margin-bottom: 0px">
            <div class="config-tag-list">
              <el-tag
                v-for="tag in tagList"
                :key="tag.id"
                class="config-tag-item"
                :class="{ 'config-tag-selected': addTagForm.tagIds.includes(tag.id) }"
                @click="handleAddTagSelect(tag)"
              >
                {{ tag.label_name }}
              </el-tag>
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addTagDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitAddTag">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 编辑标签对话框 -->
      <el-dialog v-model="editTagDialogVisible" title="编辑标签" width="400px" destroy-on-close class="tag-dialog">
        <el-form :model="editTagForm" label-width="80px">
          <el-form-item label="标签名称" required>
            <el-input v-model="editTagForm.name" placeholder="请输入标签名称" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editTagDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitEditTag">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 配置好友标签对话框 -->
      <el-dialog
        v-model="configFriendTagDialogVisible"
        title="批量配置标签"
        width="500px"
        destroy-on-close
        class="tag-dialog"
        @close="resetConfigFriendTagDialog"
      >
        <el-form :model="configFriendTagForm" label-width="80px" class="tag-form">
          <el-form-item :label="activeTab === 'friend' ? '选择好友' : '选择群聊'" required style="line-height: normal">
            <!-- 好友选择 -->
            <template v-if="activeTab === 'friend'">
              <friend-tag-input :selected-friends="selectedFriendsList" @click="showFriendSelectDialog" @remove="handleRemoveFriend" />
              <friend-select-dialog
                v-model="friendSelectDialogVisible"
                :multiple="true"
                :tag-list="tagList"
                :selected-friends="configFriendTagForm.friendIds"
                title="选择好友"
                @confirm="handleFriendSelectConfirm"
                @cancel="handleFriendSelectCancel"
              />
            </template>
            <!-- 群聊选择 -->
            <template v-else>
              <group-tag-input :selected-groups="selectedGroupsList" @click="showGroupSelectDialog" @remove="handleRemoveGroup" />
              <group-select-dialog
                v-model="groupSelectDialogVisible"
                :multiple="true"
                :selected-groups="configFriendTagForm.friendIds"
                title="选择群聊"
                @confirm="handleGroupSelectConfirm"
                @cancel="handleGroupSelectCancel"
              />
            </template>
          </el-form-item>
          <el-form-item label="选择标签">
            <tag-tag-input :selected-tags="selectedTagsList" @click="showTagSelectDialog" @remove="handleRemoveTagFromConfig" />
            <tag-select-dialog
              v-model="tagSelectDialogVisible"
              :multiple="true"
              :selected-tags="configFriendTagForm.tagIds"
              title="选择标签"
              @confirm="handleTagSelectConfirm"
              @cancel="handleTagSelectCancel"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="configFriendTagDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitConfigFriendTag">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </el-config-provider>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Lock, PriceTag } from '@element-plus/icons-vue';
import { getAllLabel, addLabel, updateLabel, deleteLabel, updateUserLabel, getCustomerLabel } from '@/api/userRate/label';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import FriendSelectDialog from '@/components/FriendSelect/FriendSelectDialog.vue';
import FriendTagInput from '@/components/FriendSelect/FriendTagInput.vue';
import GroupSelectDialog from '@/components/GroupSelect/GroupSelectDialog.vue';
import GroupTagInput from '@/components/GroupSelect/GroupTagInput.vue';
import { TagSelectDialog, TagTagInput } from '@/components/TagSelect';
import Pagination from '@/components/Pagination/index.vue';
import AiWechatInfo from '@/components/AiWechatInfo/index.vue';
import FilterForm from '@/components/FilterForm/index.vue';
import type { FormItem } from '@/components/FilterForm/index.vue';

interface Tag {
  id: string;
  label_name: string;
}

interface Friend {
  id: string;
  avatar: string;
  nickname: string;
  remark: string;
  tags: Tag[];
  myWxId: string;
  sendWxId: string;
  memberCount?: number;
  groupUrlList?: string[]; // 添加群成员头像列表
}

interface ApiFriend {
  id: number;
  customerUrl: string;
  user_id: string;
  customer_id: string;
  customerName: string;
  wx_account: string;
  labels: {
    id: number;
    label_name: string;
  }[];
}

interface ApiGroup {
  groupMemberCount: number;
  wx_account: string;
  user_id: string;
  customer_id: string;
  customerName: string;
  labels: {
    id: number;
    label_name: string;
  }[];
}

const wxId = ref('');
// 活动选项卡
const activeTab = ref<'friend' | 'group'>('friend');

// 筛选表单
const filterForm = reactive({
  customerName: '',
  labels: [] as string[]
});

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 加载状态
const loading = ref(false);

// 标签列表
const tagList = ref<Tag[]>([]);

// 当前页数据
const friendList = ref<Friend[]>([]);

// 新增标签对话框
const createTagDialogVisible = ref(false);
const newTagInput = ref('');

// 添加标签对话框
const addTagDialogVisible = ref(false);
const addTagForm = reactive({
  tagIds: [] as string[]
});
const currentFriend = ref<Friend | null>(null);

// 编辑标签相关
const editTagDialogVisible = ref(false);
const editTagForm = reactive({
  id: '',
  name: ''
});

// 配置好友标签对话框
const configFriendTagDialogVisible = ref(false);
const configFriendTagForm = reactive({
  friendIds: [] as string[],
  tagIds: [] as string[]
});

// 好友选择弹窗
const friendSelectDialogVisible = ref(false);
const selectedFriendsList = ref<any[]>([]);

// 群组选择弹窗
const groupSelectDialogVisible = ref(false);
const selectedGroupsList = ref<any[]>([]);

// 标签选择弹窗
const tagSelectDialogVisible = ref(false);
const selectedTagsList = ref<any[]>([]);

// 筛选标签选择弹窗
const filterTagSelectDialogVisible = ref(false);

// 在 script setup 部分添加
const friendSearchInput = ref('');

// 扩展FormItem类型
interface ExtendedFormItem extends FormItem {
  events?: {
    [key: string]: (...args: any[]) => void;
  };
}

// 信息列标题
const infoColumnLabel = computed(() => (activeTab.value === 'friend' ? '好友信息' : '群聊信息'));

// 表单项配置
const formItems = computed<ExtendedFormItem[]>(() => [
  {
    type: 'input',
    label: activeTab.value === 'friend' ? '用户名称' : '群聊名称',
    prop: 'customerName',
    placeholder: activeTab.value === 'friend' ? '请输入用户名称' : '请输入群聊名称'
  },
  {
    type: 'custom',
    label: '标签名称',
    prop: 'labels',
    component: TagTagInput,
    props: {
      placeholder: '请选择标签',
      selectedTags: tagList.value.filter((tag) => filterForm.labels.includes(tag.id))
    },
    events: {
      click: () => showFilterTagSelectDialog(),
      remove: (tag: Tag) => handleRemoveFilterTag(tag)
    }
  }
]);

// 获取所有标签
const fetchTags = async () => {
  try {
    const res = await getAllLabel(filterForm.customerName);
    tagList.value = res.data.map((item: any) => ({
      id: item.id.toString(),
      label_name: item.label_name
    }));
  } catch (error) {
    ElMessage.error('获取标签列表失败');
  }
};

// 获取列表
const handleSearch = async (formData?: Record<string, any>) => {
  try {
    loading.value = true;
    // 使用传入的表单数据或当前的表单数据
    const searchData = formData || filterForm;

    // 处理 labels 参数，确保是字符串格式
    let labelsParam = undefined as string | undefined;
    if (filterForm.labels) {
      if (Array.isArray(filterForm.labels)) {
        labelsParam = filterForm.labels.length > 0 ? filterForm.labels.join(',') : undefined;
      } else if (typeof filterForm.labels === 'string' && String(filterForm.labels).trim()) {
        labelsParam = String(filterForm.labels);
      }
    }

    const params: any = {
      wxId: wxId.value,
      customerName: searchData.customerName || undefined,
      labels: labelsParam,
      current: currentPage.value,
      size: pageSize.value,
      type: activeTab.value === 'friend' ? '1' : '2'
    };

    // 移除所有 undefined 的参数
    Object.keys(params).forEach((key) => {
      if (params[key as keyof typeof params] === undefined) {
        delete params[key as keyof typeof params];
      }
    });

    const res = await getCustomerLabel(params);
    if (res.data && res.data.records) {
      if (activeTab.value === 'friend') {
        const filteredData = (res.data.records as ApiFriend[]).map((item) => ({
          id: String(item.id ?? item.customer_id),
          avatar: (item as any).customerUrl || '',
          nickname: item.customerName,
          remark: item.wx_account || '-',
          tags: (item.labels || []).map((tag: any) => ({
            id: String(tag.id),
            label_name: tag.label_name
          })),
          myWxId: item.user_id,
          sendWxId: item.customer_id
        }));
        friendList.value = filteredData;
      } else {
        const filteredGroupData = (res.data.records as ApiGroup[]).map((item) => ({
          id: item.customer_id || item.wx_account,
          avatar: '',
          nickname: item.customerName,
          remark: item.wx_account || '-',
          tags: (item.labels || []).map((tag: any) => ({
            id: String(tag.id),
            label_name: tag.label_name
          })),
          myWxId: item.user_id,
          sendWxId: item.customer_id,
          memberCount: item.groupMemberCount,
          groupUrlList: (item as any).groupUrlList || [] // 添加群成员头像列表
        }));
        friendList.value = filteredGroupData;
      }
      total.value = res.data.total;
      currentPage.value = res.data.current;
      pageSize.value = res.data.size;
    } else {
      ElMessage.error('获取列表失败');
    }
  } catch (error) {
    console.error('获取列表失败:', error);
    ElMessage.error('获取列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 选项卡切换
const handleTabClick = async () => {
  currentPage.value = 1;
  pageSize.value = 10;
  await handleSearch();
};

// 初始化
onMounted(() => {
  wxId.value = JSON.parse(localStorage.getItem('msgprofile') || '{}').wx_id;
  fetchTags();
  handleSearch();
});

// 重置筛选
const resetFilter = () => {
  filterForm.customerName = '';
  filterForm.labels = [];
  currentPage.value = 1;
  pageSize.value = 10;
  handleSearch();
};

// 新增标签
const handleCreateTag = () => {
  createTagDialogVisible.value = true;
  newTagInput.value = '';
  fetchTags(); // 重新获取已配置的标签
};

// 添加新标签
const handleAddNewTag = async () => {
  const tag = newTagInput.value.trim();
  if (!tag) return;

  // 检查是否为受保护的标签名称
  if (isProtectedTag(tag)) {
    ElMessage.warning('该标签名称为系统预设标签，请使用其他名称');
    return;
  }

  // 检查是否已存在（包括已配置的标签）
  const isDuplicate = tagList.value.some((t) => t.label_name === tag);

  if (isDuplicate) {
    ElMessage.warning('该标签已存在');
    return;
  }

  try {
    // 直接调用API保存标签
    await addLabel(tag);
    ElMessage.success('标签添加成功');
    newTagInput.value = '';
    // 重新获取标签列表
    await fetchTags();
  } catch (error) {
    ElMessage.error('添加标签失败');
  }
};

// 编辑标签
const handleAddTag = (friend: Friend) => {
  currentFriend.value = friend;
  addTagForm.tagIds = friend.tags.map((tag) => tag.id);
  addTagDialogVisible.value = true;
};

// 提交添加标签
const submitAddTag = async () => {
  if (!currentFriend.value) return;

  try {
    await updateUserLabel(addTagForm.tagIds.join(','), currentFriend.value.myWxId, currentFriend.value.sendWxId, '0');
    addTagDialogVisible.value = false;
    ElMessage.success('标签添加成功');
    await handleSearch();
  } catch (error) {
    ElMessage.error('添加标签失败');
  }
};

// 移除标签
const handleRemoveTag = async (friend: Friend, tag: Tag) => {
  try {
    const newTagIds = friend.tags.filter((t) => t.id !== tag.id).map((t) => t.id);

    await updateUserLabel(newTagIds.join(','), friend.myWxId, friend.sendWxId, '0');
    ElMessage.success('标签移除成功');
    await handleSearch();
  } catch (error) {
    ElMessage.error('移除标签失败');
  }
};

// 编辑标签
const handleEditTag = (tag: Tag) => {
  // 检查是否为受保护的标签
  if (isProtectedTag(tag.label_name)) {
    ElMessage.warning('该标签为系统预设标签，不允许编辑');
    return;
  }

  editTagForm.id = tag.id;
  editTagForm.name = tag.label_name;
  editTagDialogVisible.value = true;
};

// 提交编辑标签
const submitEditTag = async () => {
  if (!editTagForm.name.trim()) {
    ElMessage.warning('请输入标签名称');
    return;
  }

  // 检查是否与其他标签重复
  const isDuplicate = tagList.value.some((t) => t.id !== editTagForm.id && t.label_name === editTagForm.name);

  if (isDuplicate) {
    ElMessage.warning('该标签名称已存在');
    return;
  }

  try {
    await updateLabel(editTagForm.id, editTagForm.name);
    editTagDialogVisible.value = false;
    ElMessage.success('标签更新成功');
    await fetchTags();
  } catch (error) {
    ElMessage.error('更新标签失败');
  }
};

// 受保护的标签列表
const protectedTags = ['高意向客户', '低意向客户', '待定客户'];

// 检查是否为受保护的标签
const isProtectedTag = (tagName: string) => {
  return protectedTags.includes(tagName);
};

// 删除标签
const handleDeleteTag = async (tag: Tag) => {
  // 检查是否为受保护的标签
  if (isProtectedTag(tag.label_name)) {
    ElMessage.warning('该标签为系统预设标签，不允许删除');
    return;
  }

  try {
    await ElMessageBox.confirm('确定要删除该标签吗？删除后不可恢复。', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await deleteLabel(tag.id);
    ElMessage.success('标签删除成功');
    await fetchTags();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除标签失败');
    }
  }
};

// 处理分页变化
const handlePagination = ({ pageNum, pageSize: size }: { pageNum: number; pageSize: number }) => {
  currentPage.value = pageNum;
  pageSize.value = size;
  handleSearch();
};

// 修改 showFriendSelectDialog 函数
const showFriendSelectDialog = () => {
  friendSelectDialogVisible.value = true;
};

// 添加 showGroupSelectDialog 函数
const showGroupSelectDialog = () => {
  groupSelectDialogVisible.value = true;
};

// 修改 handleFriendSelectConfirm 函数
const handleFriendSelectConfirm = (selectedFriends: any[]) => {
  // 合并去重
  const wxIdSet = new Set(selectedFriendsList.value.map((f) => f.wx_id));
  selectedFriends.forEach((friend) => {
    if (!wxIdSet.has(friend.wx_id)) {
      selectedFriendsList.value.push(friend);
      wxIdSet.add(friend.wx_id);
    }
  });
  configFriendTagForm.friendIds = selectedFriendsList.value.map((friend) => friend.wx_id);
  updateInputDisplay();
};

// 修改 handleFriendSelectCancel 函数
const handleFriendSelectCancel = () => {
  friendSelectDialogVisible.value = false;
};

// 修改 handleRemoveFriend 函数
const handleRemoveFriend = (friend: any) => {
  const index = selectedFriendsList.value.findIndex((f) => f.wx_id === friend.wx_id);
  if (index > -1) {
    selectedFriendsList.value.splice(index, 1);
    configFriendTagForm.friendIds = selectedFriendsList.value.map((f) => f.wx_id);
    updateInputDisplay();
  }
};

// 修改 handleGroupSelectConfirm 函数
const handleGroupSelectConfirm = (selectedGroups: any[]) => {
  // 合并去重
  const wxIdSet = new Set(selectedGroupsList.value.map((g) => g.wx_id));
  selectedGroups.forEach((group) => {
    if (!wxIdSet.has(group.wx_id)) {
      selectedGroupsList.value.push(group);
      wxIdSet.add(group.wx_id);
    }
  });
  configFriendTagForm.friendIds = selectedGroupsList.value.map((group) => group.wx_id);
  updateInputDisplay();
};

// 修改 handleGroupSelectCancel 函数
const handleGroupSelectCancel = () => {
  groupSelectDialogVisible.value = false;
};

// 修改 handleRemoveGroup 函数
const handleRemoveGroup = (group: any) => {
  const index = selectedGroupsList.value.findIndex((g) => g.wx_id === group.wx_id);
  if (index > -1) {
    selectedGroupsList.value.splice(index, 1);
    configFriendTagForm.friendIds = selectedGroupsList.value.map((g) => g.wx_id);
    updateInputDisplay();
  }
};

// 修改 updateInputDisplay 函数
const updateInputDisplay = () => {
  let displayContent: string[] = [];

  if (activeTab.value === 'friend') {
    const friendNames = selectedFriendsList.value.map((friend) => friend.nick_name);
    if (friendNames.length > 0) {
      displayContent.push(`好友：${friendNames.join('、')}`);
    }
  } else {
    const groupNames = selectedGroupsList.value.map((group) => group.name);
    if (groupNames.length > 0) {
      displayContent.push(`群聊：${groupNames.join('、')}`);
    }
  }

  const selectedTags = tagList.value.filter((tag) => configFriendTagForm.tagIds.includes(tag.id)).map((tag) => tag.label_name);
  if (selectedTags.length > 0) {
    displayContent.push(`标签：${selectedTags.join('、')}`);
  }

  friendSearchInput.value = displayContent.join(' | ');
};

// 修改 handleConfigFriendTag 函数
const handleConfigFriendTag = () => {
  configFriendTagForm.friendIds = [];
  configFriendTagForm.tagIds = [];
  selectedFriendsList.value = [];
  friendSearchInput.value = '';
  configFriendTagDialogVisible.value = true;
};

// 提交配置好友标签
const submitConfigFriendTag = async () => {
  if (configFriendTagForm.friendIds.length === 0) {
    ElMessage.warning('请选择好友');
    return;
  }

  try {
    // 将选中的好友ID用逗号拼接
    const sendWxIds = configFriendTagForm.friendIds.join(',');
    // 一次性更新所有选中好友的标签
    await updateUserLabel(configFriendTagForm.tagIds.join(','), wxId.value, sendWxIds, '1');
    configFriendTagDialogVisible.value = false;
    ElMessage.success('配置标签成功');
    await handleSearch();
  } catch (error) {
    ElMessage.error('配置标签失败');
  }
};

// 处理标签选择
const handleAddTagSelect = (tag: Tag) => {
  const index = addTagForm.tagIds.indexOf(tag.id);
  if (index > -1) {
    addTagForm.tagIds.splice(index, 1);
  } else {
    addTagForm.tagIds.push(tag.id);
  }
};

// 标签选择相关方法
const showTagSelectDialog = () => {
  tagSelectDialogVisible.value = true;
};

const handleTagSelectConfirm = (selectedTags: any[]) => {
  selectedTagsList.value = selectedTags;
  configFriendTagForm.tagIds = selectedTags.map((tag) => tag.id);
};

const handleTagSelectCancel = () => {
  tagSelectDialogVisible.value = false;
};

const handleRemoveTagFromConfig = (tag: any) => {
  const index = selectedTagsList.value.findIndex((t) => t.id === tag.id);
  if (index > -1) {
    selectedTagsList.value.splice(index, 1);
    configFriendTagForm.tagIds = selectedTagsList.value.map((t) => t.id);
  }
};

// 在 script 末尾添加
const resetConfigFriendTagDialog = () => {
  configFriendTagForm.friendIds = [];
  configFriendTagForm.tagIds = [];
  selectedFriendsList.value = [];
  selectedGroupsList.value = [];
  selectedTagsList.value = [];
  friendSearchInput.value = '';
};

// 筛选标签选择相关方法
const showFilterTagSelectDialog = () => {
  filterTagSelectDialogVisible.value = true;
};

const handleFilterTagSelectConfirm = (selectedTags: Tag[]) => {
  filterForm.labels = selectedTags.map((tag) => tag.id);
};

const handleRemoveFilterTag = (tag: Tag) => {
  filterForm.labels = filterForm.labels.filter((id) => id !== tag.id);
};
</script>

<style lang="scss" scoped>
.tag-manage {
  padding: 20px;
  min-height: calc(100vh - 40px);

  .operation-section {
    margin-bottom: 20px;
    display: flex;
    gap: 12px;
  }

  .table-section {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .operation-section {
      margin-bottom: 16px;
      display: flex;
      align-items: center;
    }

    .custom-table {
      :deep(.el-table__header) {
        th {
          background-color: #f5f7fa;
          color: #606266;
          font-weight: 600;
        }
      }

      :deep(.el-table__row) {
        &:hover {
          td {
            background-color: #f5f7fa;
          }
        }
      }
    }
  }

  .tag-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;

    .tag-item {
      margin: 0;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        opacity: 0.8;
      }
    }
  }
}

// 群聊信息居中布局
.group-info-centered {
  display: flex;
  // flex-direction: column;
  align-items: center;
  text-align: center;
  width: 70%;
  margin: 0 auto;
  gap: 8px;
}

.group-avatar-centered {
  margin-bottom: 8px;

  .group-avatar {
    width: 40px;
    height: 40px;
    border-radius: 8px;
    border: 1px solid #fff;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
    transition: transform 0.3s ease;

    &:hover {
      transform: scale(1.03);
    }
  }
}

.group-name-centered {
  font-size: 15px;
  font-weight: 600;
  color: #2c3e50;
  line-height: 1.3;
  transition: color 0.3s ease;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;

  &:hover {
    color: #409eff;
  }
}

// 保留原有样式用于兼容
.group-info-container {
  display: flex;
  align-items: center;
  gap: 12px;
}

.group-avatar-container,
.friend-avatar-container {
  flex-shrink: 0;
}

.friend-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.group-avatar {
  width: 40px;
  height: 40px;
  display: grid;
  gap: 1px;
  border-radius: 8px;
  overflow: hidden;
  padding: 2px;
  place-items: center;

  &.avatar-count-1 {
    grid-template-columns: 1fr;
    grid-template-rows: 1fr;
  }

  &.avatar-count-2 {
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: 1fr;
  }

  &.avatar-count-3 {
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(2, 1fr);

    .group-avatar-item {
      width: 100%;
      height: 100%;

      &:first-child {
        grid-column: 1 / -1;
        width: 50%;
        margin: 0 auto;
      }
    }
  }

  &.avatar-count-4 {
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(2, 1fr);
  }

  &.avatar-count-5 {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: repeat(2, 1fr);
    gap: 2px;

    .group-avatar-item {
      width: 100%;
      height: 100%;

      &:nth-child(1) {
        grid-column: 1 / 2;
        transform: translateX(50%);
      }
      &:nth-child(2) {
        grid-column: 2 / 3;
        transform: translateX(50%);
      }
      &:nth-child(3) {
        grid-column: 1 / 2;
      }
      &:nth-child(4) {
        grid-column: 2 / 3;
      }
      &:nth-child(5) {
        grid-column: 3 / 4;
      }
    }
  }

  &.avatar-count-6 {
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: repeat(2, 1fr);
  }

  &.avatar-count-7 {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: repeat(3, 1fr);

    .group-avatar-item {
      width: 100%;
      height: 100%;

      &:nth-child(1) {
        grid-column: 2 / 3;
      }
      &:nth-child(2) {
        grid-column: 1 / 2;
      }
      &:nth-child(3) {
        grid-column: 2 / 3;
      }
      &:nth-child(4) {
        grid-column: 3 / 4;
      }
      &:nth-child(5) {
        grid-column: 1 / 2;
      }
      &:nth-child(6) {
        grid-column: 2 / 3;
      }
      &:nth-child(7) {
        grid-column: 3 / 4;
      }
    }
  }

  &.avatar-count-8 {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: repeat(3, 1fr);

    .group-avatar-item {
      width: 100%;
      height: 100%;

      &:nth-child(1) {
        grid-column: 1 / 2;
        transform: translateX(50%);
      }
      &:nth-child(2) {
        grid-column: 2 / 3;
        transform: translateX(50%);
      }
      &:nth-child(3) {
        grid-column: 1 / 2;
      }
      &:nth-child(4) {
        grid-column: 2 / 3;
      }
      &:nth-child(5) {
        grid-column: 3 / 4;
      }
      &:nth-child(6) {
        grid-column: 1 / 2;
      }
      &:nth-child(7) {
        grid-column: 2 / 3;
      }
      &:nth-child(8) {
        grid-column: 3 / 4;
      }
    }
  }

  &.avatar-count-9 {
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: repeat(3, 1fr);
  }

  .group-avatar-item {
    width: 100%;
    overflow: hidden;
    border-radius: 2px;
    display: flex;
    align-items: center;
    justify-content: center;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
}

.group-info-text {
  display: flex;
  flex-direction: column;
  line-height: 1.4;
  flex: 1;

  .name {
    font-weight: 600;
    color: #2c3e50;
  }
  .wxid {
    font-size: 12px;
    color: #606266;
  }
}

.tag-dialog {
  :deep(.el-dialog__body) {
    padding: 20px 30px;
  }

  .tag-form {
    .el-form-item {
      margin-bottom: 22px;
    }

    .tag-select {
      width: 100%;
    }
  }
}

.tag-content {
  .section-title {
    font-size: 14px;
    font-weight: 500;
    color: #606266;
    margin-bottom: 12px;
  }

  .existing-tags {
    margin-bottom: 24px;
  }

  .tag-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }

  .new-tags {
    .tag-input {
      margin-bottom: 12px;
    }

    .new-tag-list {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }
  }

  .tag-item {
    margin: 0;

    &.protected-tag {
      background-color: #f0f9ff;
      border-color: #0ea5e9;
      color: #0369a1;

      .protected-icon {
        margin-left: 4px;
        font-size: 12px;
      }
    }

    .clickable {
      cursor: pointer;

      &:hover {
        opacity: 0.8;
      }
    }

    span:not(.clickable) {
      cursor: default;
    }
  }
}

:deep(.el-button) {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.config-tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;

  .config-tag-item {
    margin: 0;
    cursor: pointer;
    transition: all 0.3s;
    background-color: #f4f4f5;
    border-color: #e9e9eb;
    color: #606266;

    &:hover {
      background-color: #e9e9eb;
      border-color: #dcdfe6;
    }

    &.config-tag-selected {
      background-color: #ecf5ff;
      border-color: #409eff;
      color: #409eff;
    }
  }
}

.selected-friends {
  margin-top: 12px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;

  .friend-tag {
    margin: 0;
    display: flex;
    align-items: center;
    gap: 4px;
    padding: 0 8px;
    height: 28px;
    line-height: 26px;
    border-radius: 4px;
    background-color: #f0f9eb;
    border-color: #e1f3d8;
    color: #67c23a;

    &:hover {
      background-color: #e1f3d8;
    }
  }
}

.tag-form {
  .el-form-item {
    margin-bottom: 22px;
  }
}

.tag-input-wrapper {
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 0 8px;
  display: flex;
  align-items: center;
  cursor: pointer;
  background-color: #fff;
  transition: all 0.3s;

  &:hover {
    border-color: #c0c4cc;
  }

  .tag-input-content {
    flex: 1;
    min-height: 32px;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
  }

  .placeholder {
    color: #c0c4cc;
    font-size: 14px;
  }

  .search-icon {
    color: #c0c4cc;
    font-size: 16px;
    margin-left: 8px;
    cursor: pointer;

    &:hover {
      color: #409eff;
    }
  }

  .input-tag {
    margin: 3px;
    height: 24px;
    line-height: 22px;
    padding: 0 8px;
    font-size: 12px;
  }
}

// 参照 wechatNotice 的选项卡外观
.notice-tabs {
  margin-top: 20px;
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

  :deep(.el-tabs__header) {
    margin: 0;
    padding: 0;
  }

  :deep(.el-tabs__content) {
    padding: 0;
    margin-top: 15px;
  }
}
</style>
